<?php

/**
 * Stargame 授权
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class StargameSDK extends Common\Util\ThinkSDK\ThinkOauth{
    /**
     * 获取requestCode的api接口
     */
    protected $GetRequestCodeURL = 'https://passport.stargame.com/oauth/authorize';

    /**
     * 获取access_token的api接口
     */
    protected $GetAccessTokenURL = 'https://passport.stargame.com/oauth/token';

    protected $GetOpenIdUrl = 'https://passport.stargame.com/api/openid';

    protected $GetUserInfoUrl = 'https://passport.stargame.com/api/user/info';

    public function code($redirect_url = '', $state='')
    {
        $param =  ['channel'=>'stargame'];
        // $redirect_url && $param['redirect_url'] =  base64_encode($redirect_url);
        $redirect = U('Home/Sso/code', $param, false, true);
        $redirect = urlencode($redirect);
        return "{$this->GetRequestCodeURL}?client_id=".$this->AppKey."&redirect_uri={$redirect}&response_type=code&state={$state}";
    }

    public function call($api, $param = '', $method = 'GET', $multi = false) {
    }

    public function parseExtend($request)
    {
        $extend = null;
        if ($request['access_token'] && $request['openid']){
            $extend = array_filter_by_array($request, ['access_token', 'openid', 'nickname', 'avatar']);
        }
        return $extend;
    }

    /**
     * 解析access_token方法请求后的返回值 
     * @param string $result 获取access_token的方法的返回值
     */
    protected function parseToken($result, $extend) {
        $data = json_decode($result, true);
        if($data['access_token'] && $data['token_type'] && $data['expires_in']){
            $this->Token = $data;
            $data['openid'] = $this->openid();
            $userinfo = $this->userinfo($data['access_token'], $data['openid']);
            $data = array_merge($data, $userinfo);
            return $data;
        } else
            throw new Exception("获取 Google ACCESS_TOKEN出错：未知错误");
    }

    /**
     * 获取当前授权应用的openid
     * @return string
     */
    public function openid() {
        $data = $this->Token;
        if ($data['access_token']) {
            $data = $this->http($this->GetOpenIdUrl, array('access_token' => $data['access_token']));

            $data = json_decode($data, true);
            if (isset($data['openid']))
                return $data['openid'];
            else
                throw new Exception("获取用户openid出错！");
        } else {
            throw new Exception('没有获取到openid！');
        }
    }

    /**
     * 获取access_token
     * 重写ThinkOauth的getAccessToken()方法
     * @param string $code 上一步请求到的code
     */
    public function getAccessToken($code, $extend = null){
        $this->config();
        $params = array(
                'client_id'     => $this->AppKey,
                'client_secret' => $this->AppSecret,
                'grant_type'    => $this->GrantType,
                'code'          => $code,
                'redirect_uri'  => $this->Callback,
                // 'redirect_uri'  => cookie('stargame_callback'),
        );
        $data = $this->http($this->GetAccessTokenURL, $params, 'POST');
        $this->Token = $this->parseToken($data, $extend);
        return $this->Token;
    }

    public function userinfo($access_token, $openid) {
        $param = [
            'access_token' => $access_token,
            'openid'       => $openid,
        ];
        $data = $this->http($this->GetUserInfoUrl, $param);

        $data = json_decode($data, true);
        if (isset($data['nickname']) && isset($data['avatar'])) {
            return [
                'userId'       => $data['id'],
                'nickname' => $data['nickname'],
                'avatar'   => $data['avatar']
            ];
        }
        return [];
    }
}